import React, { Component } from 'react'
import {List,Badge,} from 'antd-mobile'
import { connect } from 'react-redux'
import moment from 'moment'
import QueueAnim from 'rc-queue-anim'
const Item = List.Item
const Brief = Item.Brief


class Message extends Component{
    getLastMsgs(chatMsgs,userId) {
        let lastMsgsObj = { }
        if (chatMsgs.length>0 ){
            chatMsgs.forEach(msg => {
                !msg.read && msg.to === userId? msg.unReadCount = 1 : msg.unReadCount = 0
                const lastMsg = lastMsgsObj[msg.chat_id]
                if(!lastMsg){
                    lastMsgsObj[msg.chat_id] = msg
                }else {
                    const unReadCount = lastMsg.unReadCount + msg.unReadCount
                    if (msg.create_time-lastMsg.create_time){
                        lastMsgsObj[msg.chat_id] = msg
                    }
                    lastMsgsObj[msg.chat_id].unReadCount = unReadCount
                }
            })
        }
        const lastMsgs = Object.values(lastMsgsObj)
        lastMsgs.sort(function (m1, m2) {
            return   m2.create_time - m1.create_time
        })
        return lastMsgs
    }
    render() {
        const { user, chat } = this.props
        const { users, chatMsgs } = chat
        const lastMsg = this.getLastMsgs(chatMsgs,user._id)
        return(
            <div style={{marginTop:45,marginBottom:50}}>
                <List>
                    <QueueAnim type='left'>
                        {
                            lastMsg.map( msg =>{
                                const targetId = msg.from === user._id? msg.to: msg.from
                                const targetUser = users[targetId]
                                return(
                                    <Item
                                        key={ msg.chat_id }
                                        extra={<Badge text={msg.unReadCount}/>}
                                        thumb={ require(`../../assets/avatars/${targetUser.avatar }.png`).default}
                                        arrow="horizontal"
                                        onClick={()=>this.props.history.push(`/chat/${targetId}`)}
                                    >
                                        <span style={{ marginLeft: 12 }}>{targetUser.username}</span>
                                        <Brief style={{ marginLeft: 12 }}>{ msg.content }</Brief>
                                        <Brief style={{ marginLeft: 12 }}>{ moment(msg.create_time).format(' h:m:s a')}</Brief>
                                    </Item>
                                )
                            })
                        }
                    </QueueAnim>
                </List>
            </div>
        )
    }
}
export default connect(
    state=>({
        user:state.user,
        chat:state.chat
    }),
    {}
)(Message)